﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace tx_reseau
{
    public partial class frmTX : Form
    {
        public frmTX()
        {
            InitializeComponent();
            
        }

        /// <summary>
        /// Fonction _Click du bouton d'envoi.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEnvoyer_Click(object sender, EventArgs e)
        {
            EnvoieTrame(txtMessage.Text, txtIPRx.Text, txtPort.Text);
        }


        /// <summary>
        /// Envoie la trame spécifiée à l'ordinateur distant.
        /// </summary>
        /// <param name="Trame">Trame à envoyer.</param>
        /// <param name="IPAdd">L'adresse IP de l'ordinateur distant.</param>
        /// <param name="Port">Le port d'écoute de l'ordinateur distant.</param>
        /// <returns></returns>
        private bool EnvoieTrame(string Trame, string IPAdd, string Port)
        {
            Socket sock = null;

            int nPortRX = Convert.ToInt16(Port);

            byte[] bTexte = Encoding.ASCII.GetBytes(Trame);

            EndPoint PointLocal = new IPEndPoint(0, 9998);
            IPAddress IPDistant;

            if (!IPAddress.TryParse(IPAdd, out IPDistant))
            {
                MessageBox.Show("Erreur, addresse IP invalide.");
                return false;
            }
            
            EndPoint PointDistant = new IPEndPoint(IPDistant, nPortRX);


            try
            {
                if (sock == null)
                {
                    sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sock.Bind(PointLocal);
                }

                sock.SendTo(bTexte, bTexte.Length, SocketFlags.None, PointDistant);
            }
            catch (SocketException e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
            sock.Close();

            return true;
        }

    }
}
